<?php

namespace app\health\controller;

use app\health\model\HealthCouponList;
use app\health\model\HealthGoodsAttr;
use app\health\model\HealthOrder;
use app\health\model\HealthUser;
use app\health\model\HealthUserAddress;
use app\health\service\WePayService;
use app\health\validate\OrderValidate;
use Exception;
use think\Db;
use think\Hook;

class Order extends ApiBase
{
    /**
     * 确认订单信息
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function confirmInfo()
    {
        $params            = (new OrderValidate())->goCheck('confirm_info');
        $params['user_id'] = $this->auth->id;
        $this->success('', HealthOrder::confirmInfo($params));
    }

    /**
     * 获取可使用优惠券列表
     * @Author 张旭鹏
     * @DateTime 2023-06-19
     */
    public function coupons()
    {
        $params = (new OrderValidate())->goCheck('confirm_info', ['user_id' => $this->auth->id]);
        $this->success('获取成功', HealthOrder::coupons($params));
    }

    /**
     * 创建订单
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function createOrder()
    {
        $confirmType = $this->request->param('confirm_type', 1);
        $cart_id     = $this->request->param('cart_id', []);
        if (is_string($cart_id)) {
            $cart_id = explode(',', $cart_id);
        }
        $params           = (new OrderValidate())->goCheck('create_order', ['user_id' => $this->auth->id, 'confirm_type' => $confirmType, 'cart_id' => $cart_id]);
        $orderNo          = create_trade_no('C');
        $orderConfirmInfo = HealthOrder::confirmInfo($params);
        $addressInfo      = HealthUserAddress::where('id', $params['address_id'])->find();
        try {
            Db::startTrans();
            $orderData      = [
                'order_no'         => $orderNo,
                'user_id'          => $params['user_id'],
                'mobile'           => $addressInfo['mobile'],
                'username'         => $addressInfo['username'],
                'province'         => $addressInfo['province_name'],
                'city'             => $addressInfo['city_name'],
                'county'           => $addressInfo['county_name'],
                'address'          => $addressInfo['address'],
                'housenumber'      => $addressInfo['housenumber'],
                'address_id'       => $params['address_id'],
                'status'           => 1,
                'total_price'      => $orderConfirmInfo['total_price'],
                'pay_price'        => $orderConfirmInfo['pay_price'],
                'discount_price'   => $orderConfirmInfo['discount_price'],
                'discount_balance' => $orderConfirmInfo['discount_balance'],
                'pay_status'       => 0,
                'coupon_list_id'   => $params['coupon_list_id'] ?? 0,
                'create_time'      => time()
            ];
            $orderGoodsData = [];
            foreach ($orderConfirmInfo['goods_lists'] as $goods) {
                $orderGoodsData[] = [
                    'goods_id'       => $goods['id'],
                    'goods_name'     => $goods['goods_name'],
                    'goods_attr_id'  => $goods['attr_id'],
                    'attr_name'      => $goods['attr_name'],
                    'image'          => $goods['image'],
                    'price'          => $goods['attr_price'],
                    'number'         => $goods['number'],
                    'discount_price' => $goods['discount_price']
                ];
                // 规格减库存
                // HealthGoodsAttr::where('id', $goods['attr_id'])->setDec('stock', $goods['number']);
            }
            // 创建订单
            $order = HealthOrder::create($orderData);
            $order->orderGoods()->saveAll($orderGoodsData);
            if ($order->discount_balance > 0) {
                HealthUser::where('id', $this->auth->id)->setDec('balance', $order->discount_balance);
            }
            // 使用优惠券
            if ($order['coupon_list_id'] > 0) {
                HealthCouponList::where('id', $order['coupon_list_id'])->update([
                    'status'   => 1,
                    'order_id' => $order['id'],
                    'use_time' => time()
                ]);
            }
            $listenParams = ['order_id' => $order->id, 'cart_id' => $orderConfirmInfo['cart_id']];
            // 订单创建成功后
            Hook::listen('order_create_after', $listenParams);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $params = [];
        if ($order->pay_price == 0) {
            $order = HealthOrder::paySuccess($order);
        } else {
            $params = WePayService::WePayOrder()->create([
                'body'         => '购买商品',
                'out_trade_no' => $order->order_no,
                'total_fee'    => APP_ENV === 'dev' ? 1 : bcmul($order->pay_price, 100),
                'openid'       => $this->auth->openid,
                'trade_type'   => 'JSAPI',
                'attach'       => 'mode=goods_order',
                'notify_url'   => request()->domain() . '/health/notify/wepay',
            ]);
            if (empty($params['prepay_id'])) {
                $this->error('微信支付创建失败');
            }
            $params = WePayService::WePayOrder()->jsapiParams($params['prepay_id']);
        }
        if ($order === false) {
            $this->error('订单创建失败');
        }
        $this->success('', ['status' => $order->status, 'order_id' => $order->id, 'params' => $params]);
    }

    /**
     * 获取支付参数
     * @Author 张旭鹏
     * @DateTime 2023-06-25
     */
    public function pay()
    {
        $params = (new OrderValidate())->goCheck('pay', ['user_id' => $this->auth->id]);
        $order  = HealthOrder::where('id', $params['order_id'])->where('user_id', $params['user_id'])->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['status'] == '5') {
            $this->error('订单已取消');
        }
        if ($order['status'] != '1') {
            $this->error('订单已支付');
        }
        $params = WePayService::WePayOrder()->create([
            'body'         => '购买商品',
            'out_trade_no' => $order->order_no,
            'total_fee'    => bcmul($order->pay_price, 100),
            'openid'       => $this->auth->openid,
            'trade_type'   => 'JSAPI',
            'attach'       => 'mode=goods_order',
            'notify_url'   => request()->domain() . '/health/notify/wepay',
        ]);
        if (empty($params['prepay_id'])) {
            $this->error('微信支付创建失败');
        }
        $params = WePayService::WePayOrder()->jsapiParams($params['prepay_id']);
        $this->success('', ['status' => $order->status, 'order_id' => $order->id, 'params' => $params]);
    }

    /**
     * 取消订单
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function cancel()
    {
        $params = (new OrderValidate())->goCheck('cancel');
        try {
            HealthOrder::cancelOrder($params['order_id'], $this->auth->id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('取消成功');
    }

    /*
	 * 确认收货
	*/
    public function confirmReceipt()
    {
        $params = (new OrderValidate())->goCheck('confirm_receipt');
        //把状态改成已完成
        try {
            HealthOrder::confirmReceipt($params['order_id'], $this->auth->id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('收货成功');
    }

    /**
     * 我的订单列表
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function lists()
    {
        $limit  = $this->request->param('limit/d', 10);
        $status = $this->request->param('status');
        $where  = [];
        if ($status) {
            $where['status'] = ['=', $status];
        }
        $paginate = HealthOrder::with(['orderGoods'])
            ->where('user_id', $this->auth->id)
            ->where($where)
            ->field('id,order_no,create_time,total_price,pay_price,status')
            ->order('id', 'desc')
            ->paginate($limit);
        $this->success('', $paginate);
    }

    /**
     * 订单详情
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function detail()
    {
        $params = (new OrderValidate())->goCheck('detail');
        $order  = HealthOrder::with(['orderGoods'])
            ->field('id,order_no,create_time,pay_price,total_price,discount_price,discount_balance,province,city,county,address_id,status,username,mobile,address,housenumber,logistics_name,express_number')
            ->where('id', $params['order_id'])
            ->where('user_id', $this->auth->id)
            ->find();
        $this->success('订单详情', $order);
    }
}
